package dictionary;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;



public class AbstractDictionary implements Dictionary {
	
	protected HashMap<String,Double> words_idf;
	private HashMap<String,Integer> word_idx;
	private ArrayList<String> words_list;
	
	public AbstractDictionary() {
		words_idf = new HashMap<String,Double>();
		words_list = new ArrayList<String>();
		word_idx = new HashMap<String,Integer>();
	}
		
	public void addWord(String word,double idf) {
		if ( !words_idf.containsKey(word) ) {
			putWord(word,idf);
		}
		else {
			Double d = words_idf.get(word);
			d += idf;
			words_idf.put(word, d);
		}
	}
	
	public void putWord(String word,double idf) {
		words_list.add(word);
		words_idf.put(word, idf);
		word_idx.put(word,word_idx.size());
	}
	
	public ArrayList<String> getAllWords() {
		return words_list;
	}

	public boolean isValidWord(String word) {
		return words_idf.containsKey(word);
	}
	
	public double getInverseFrequency(String word) {
		return words_idf.get(word);
	}
	
	public int getWordIdx(String word) {
		return word_idx.get(word);
	}

	@Override
	public String getWordAttributeEquivalent(String word) {
		return words_idf.containsKey(word)?word:null;
	}

	@Override
	public double getIdf(String word) {
		return words_idf.get(word);
	}

	@Override
	public void load(String filename) {
		BufferedReader jin = null;
		try {
			jin = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
			while ( jin.ready() ) {
				String line = jin.readLine();
				String word = line.split(" ")[0];
				double idf = Double.parseDouble(line.split(" ")[1]);
				putWord(word, idf);
			}
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			if ( jin != null )
				try {
					jin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
	
}
